import { clear } from "@testing-library/user-event/dist/clear";
import axios from "axios";
// 编写store
const { createSlice } = require("@reduxjs/toolkit");

const foodStore = createSlice({
    name: "foods",
    initialState: {
        // 商品列表
        foodsList: [],
        // 菜单激活下标值
        activeIndex: 0,
        // 购物车列表
        cartList: []
    },
    reducers: {
        // 更改商品列表
        setFoodList(state, action) {
            state.foodsList = action.payload
        },
        // 设置激活下标值
        setActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        // 更新购物车
        addCart(state, action) {
            // 是否添加过？
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        // count增
        increCount(state, action) {
            // 关键点，找到当前要修改谁的count id
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            }
        },
        // count减
        decreCount(state, action) {
            // 关键点，找到当前要修改谁的count id
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item && item.count > 0) {
                item.count--
            }
        },
        // 清除购物车
        clearCart(state, action) {
            state.cartList = []
        }
    }
})

// 异步获取部分
const { setFoodList, setActiveIndex, addCart, increCount, decreCount, clearCart } = foodStore.actions
const fetchFoodList = () => {
    return async (dispatch) => {
        // 编写异步逻辑
        const res = await axios.get("http://localhost:3004/takeaway")
        // 调用dispatch函数提交action
        dispatch(setFoodList(res.data))
    }
}

export { fetchFoodList, setActiveIndex, addCart, increCount, decreCount, clearCart }

const reducer = foodStore.reducer
export default reducer